<?php
/**
 * 会员列表
 * @return
 * @author yuncran@126.com
 */

namespace app\model;

use app\BaseModel;

use app\CacheKey;
use app\FieldKey;
use thans\jwt\facade\JWTAuth;
use think\model\concern\SoftDelete;

class UserModel extends BaseModel
{
    use SoftDelete;

    protected $pk = "id";

    protected $name = "user";

    public static $defaultField = 'id as user_id,nickname,realname as displayName,account,avatar,email,joinip,level,gender';

    protected $json = ['setting'];
    protected $jsonAssoc = true;


    public function getLevelName()
    {
        return $this->hasOne(LevelModel::class, 'id', 'level')->bind(['level_name' => field('title'), 'level_color' => 'color', 'font_color' => 'font_color', 'level_image' => 'image']);
    }

    /**
     * 余额
     * @param $user_id
     * @param $field
     * @param $size
     * @return mixed
     * @author yuncran@126.com
     */
    public static function minusUserDec($user_id, $field, $size = 1)
    {
        return self::getModel()->where('id', $user_id)->dec($field, $size)->update();
    }

    /**
     * 增加余额
     * @param $user_id
     * @param $field
     * @param $size
     * @return \think\Model|null
     * @author yuncran@126.com
     */
    public static function addUserInc($user_id, $field, $size = 1)
    {
        return self::getModel()->where('id', $user_id)->inc($field, $size)->update();
    }

    //查询用户信息
    public static function getUserInfo($map = [])
    {
        if (!$map) {
            return self::$userInfo;
        }
        $data = self::where($map)->find();
        if ($data) {
            $data = $data->toArray();
        }
        return $data;
    }


    /**
     * @param $map
     * @return UserModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public static function getUserInfoFind($map = [], $field = FieldKey::user_field_has_one)
    {
        $data = self::where($map)->field($field)->find();
        if ($data) {
            $data = $data->toArray();
        }
        return $data;
    }


    /**
     * 修改会员
     * @param $where
     * @param $data
     * @return bool
     * @author yuncran@126.com
     */
    public static function edit($where = [], $data = [])
    {
        $save = array_merge(['updatetime' => time()], $data);
        return self::getModel()->where($where)->save($save);
    }

    /**
     * 刷新用户token 之前token将被拉黑
     * 修改用户数据后 调用该方法 并返回前台更新token
     * @param array $info 用户信息
     * @param string $terminal 客户端标识
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function refreshToken($info, $terminal)
    {
        $info = str_encipher(json_encode($info), true, config('app.aes_token_key'));
        $authToken = 'bearer ' . JWTAuth::builder(['info' => $info, 'terminal' => $terminal]);
        return $authToken;
    }

    /**
     * 获取会员等级
     * @return void
     * @author yuncran@126.com
     */
    public function getLevel()
    {
        return $this->hasOne(UserLevelModel::class, 'id', 'level')->field(['id', field('title'), 'money', 'create_time']);
    }

    /**
     * 查询用户列表
     * @param $map
     * @param $user_id
     * @param $field
     * @param $keyword 搜索关键字
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public static function getUserList($map, $user_id, $field = "", $keyword)
    {
        $field = empty($field) ? self::$defaultField : $field;
        $limit = app()->request->param('limit');
        $type = app()->request->param('type');
        $user_gender = self::getModel()->where('id', $user_id)->field('id,gender')->value('gender');
        $list = self::where($map)->where('gender', '<>', $user_gender)->where('group_id', 1)->where('is_examine', 0)->field($field)
            ->append(['level_result', 'is_follow'])
            ->withAttr('level_result', function ($value, $data) {
                return UserLevelModel::where(['id' => $data['level']])->field(['id', field('title'), 'describe', 'image', 'money', 'expire', 'color', 'font_color', 'background_image', 'create_time'])->cache(CacheKey::level_title)->find();
            })
            ->withAttr('is_follow', function ($value, $data) use ($user_id) {
                $map = [['user_id', '=', $user_id], ['to_user_id', '=', $data['user_id']]];
                $result = UserFollowModel::where($map)->find();
                return empty($result) ? 2 : 1;
            })
            ->cache(true, CacheKey::home_user_list)
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('nickname', 'like', "%$keyword%");
            })
            ->when($type, function ($query) use ($type) {
                if ($type == 1) {
//                    return $query->orderRaw('RAND()');
                    return $query->orderRaw('verification ASC');
                } else {
                    return $query->orderRaw('verification ASC')->where('is_recommend', '=', 1);
                }
            })->paginate($limit)->each(function ($item) {
                return $item;
            });

        return $list;
    }


    public static function getList($map)
    {
        return self::field(self::$defaultField)->where($map)->select();
    }


    // 验证账号的合法性
    public function checkAccount(&$data)
    {
        $user_id = $data['user_id'] ?? 0;
        if ($user_id) {
            $user = self::find($data['user_id']);
            if (!$user) {
                $this->error = '账户不存在';
                return false;
            }
            $other = self::where([['account', '=', $data['account']], ['user_id', '<>', $data['user_id']]])->find();
            if ($other) {
                $this->error = '账户已存在';
                return false;
            }
        } else {
            $user = self::where('account', $data['account'])->find();
            if ($user) {
                $this->error = '账户已存在';
                return false;
            }
        }
        $data['email'] = $data['account'];
        return true;
    }


}